import datetime
import random
import time
import requests
from data import cookies,headers,csrf,host_mid

class Idstr():
    def __init__(self,id_str,orig_id_str):
        self.id_str = id_str
        self.orig_id_str = orig_id_str


def getid_strList():
    #获取首次动态列表
    response = requests.get(
        f'https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space?offset&host_mid={host_mid}&timezone_offset=-480&platform=web&features=itemOpusStyle,listOnlyfans,opusBigCover,onlyfansVote,decorationCard,forwardListHidden,ugcDelete,onlyfansQaCard&web_location=333.999&dm_img_list=[%7B%22x%22:1254,%22y%22:1465,%22z%22:0,%22timestamp%22:69,%22k%22:83,%22type%22:0%7D,%7B%22x%22:1192,%22y%22:-222,%22z%22:6,%22timestamp%22:328,%22k%22:123,%22type%22:0%7D]&dm_img_str=V2ViR0wgMS4wIChPcGVuR0wgRVMgMi4wIENocm9taXVtKQ&dm_cover_img_str=QU5HTEUgKEludGVsLCBJbnRlbChSKSBVSEQgR3JhcGhpY3MgKDB4MDAwMDhBNTYpIERpcmVjdDNEMTEgdnNfNV8wIHBzXzVfMCwgRDNEMTEpR29vZ2xlIEluYy4gKEludGVsKQ&dm_img_inter=%7B%22ds%22:[%7B%22t%22:0,%22c%22:%22%22,%22p%22:[57,19,19],%22s%22:[39,5076,5194]%7D],%22wh%22:[3660,5940,36],%22of%22:[54,108,54]%7D&x-bili-device-req-json=%7B%22platform%22:%22web%22,%22device%22:%22pc%22%7D&x-bili-web-req-json=%7B%22spm_id%22:%22333.999%22%7D&w_rid=8e093107e54b60fd35b846430c892e8e&wts=1726583398',
        cookies=cookies,
        headers=headers,
    ).json()
    data = response['data']
    id_strList = []  #保存动态列表参数值
    flag = True
    while flag:
        items = data['items']
        for item in items:
            if item.get('orig'):#因为抽奖动态都是转发的，我们原创的动态属于非转发，不会有orig数据，在此过滤掉，不做删除
                id_str = item['id_str']
                orig_id_str = item['orig']['id_str']
                new_idstr = Idstr(id_str,orig_id_str)#生成id_str对象
                id_strList.append(new_idstr)#将对象保存进列表
        offset = data['offset']#获取offset的值，以便获得后续的动态链接
        response = requests.get(
        f'https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space?offset={offset}&host_mid={host_mid}&timezone_offset=-480&platform=web&features=itemOpusStyle,listOnlyfans,opusBigCover,onlyfansVote,decorationCard,forwardListHidden,ugcDelete,onlyfansQaCard&web_location=333.999&dm_img_list=[%7B%22x%22:1254,%22y%22:1465,%22z%22:0,%22timestamp%22:69,%22k%22:83,%22type%22:0%7D,%7B%22x%22:1192,%22y%22:-222,%22z%22:6,%22timestamp%22:328,%22k%22:123,%22type%22:0%7D]&dm_img_str=V2ViR0wgMS4wIChPcGVuR0wgRVMgMi4wIENocm9taXVtKQ&dm_cover_img_str=QU5HTEUgKEludGVsLCBJbnRlbChSKSBVSEQgR3JhcGhpY3MgKDB4MDAwMDhBNTYpIERpcmVjdDNEMTEgdnNfNV8wIHBzXzVfMCwgRDNEMTEpR29vZ2xlIEluYy4gKEludGVsKQ&dm_img_inter=%7B%22ds%22:[%7B%22t%22:0,%22c%22:%22%22,%22p%22:[57,19,19],%22s%22:[39,5076,5194]%7D],%22wh%22:[3660,5940,36],%22of%22:[54,108,54]%7D&x-bili-device-req-json=%7B%22platform%22:%22web%22,%22device%22:%22pc%22%7D&x-bili-web-req-json=%7B%22spm_id%22:%22333.999%22%7D&w_rid=8e093107e54b60fd35b846430c892e8e&wts=1726583398',
            cookies=cookies,
            headers=headers,
        ).json()
        data = response['data']
        if data['has_more']:#判断是否是最后一批动态数据，如果不是，循环继续，直到has_more为false
            continue
        else:
            flag = False #当循环为false时，说明是最后一批动态数据了，我们将本次获得的动态数据加入列表就能退出循环了
            items = data['items']
            for item in items:
                if item.get('orig'):
                    id_str = item['id_str']
                    orig_id_str = item['orig']['id_str']
                    new_idstr = Idstr(id_str, orig_id_str)
                    id_strList.append(new_idstr)
        sleep_time = random.randint(1, 4)#随机生成数字1，2,3,4
        time.sleep(sleep_time)#由于爬虫速度较快，短时间发送大量请求极易被服务器判定为恶意攻击，因此随机停顿1~4秒模拟是人工操作
    return id_strList

def isAlive(orig_id_str):
    params = {
        'business_id': orig_id_str,
        'business_type': '1',
        'csrf': csrf,
        'web_location': '333.1330',
    }

    res = requests.get(
        'https://api.vc.bilibili.com/lottery_svr/v1/lottery_svr/lottery_notice',
        params=params,
        cookies=cookies,
        headers=headers,
    ).json()
    sleep_time = random.randint(1, 4)#随机生成1-4秒延迟，避免过快访问接口而被封杀
    time.sleep(sleep_time)
    data = res['data']
    timestamp =data.get('lottery_time')
    if timestamp:
        lefttime = datetime.datetime.fromtimestamp(timestamp)#格式化时间戳
        now = datetime.datetime.now()#获取当前时间
        lefts = lefttime - now#时间戳是一段int值，其实我们也可以获取现在的时间戳，两个数值相减效率可能更快，但是我想看具体开奖时间，所以用了格式化方式
        return lefts > datetime.timedelta(0)#比较时间差是否大于0
    return True#非官方抽奖工具动态默认返回True，避免删除


def remove(id_str):
    sleep_time = random.randint(1, 4)#随机停滞1-4秒
    time.sleep(sleep_time)
    params = {
        'platform': 'web',
        'csrf': csrf,
    }

    json_data = {
        'dyn_id_str': id_str,
        'dyn_type': 1,
        'rid_str': id_str,
    }
    response = requests.post(
        'https://api.bilibili.com/x/dynamic/feed/operate/remove',
        params=params,
        cookies=cookies,
        headers=headers,
        json=json_data,
    )

def main():
    id_strList = getid_strList()
    id_len = len(id_strList)
    print('您转发的总动态数为：',id_len)
    id_len = id_len-1#让删除动态从末置位开始往前删除
    while id_len>=0:
        id_item = id_strList[id_len]
        if not isAlive(id_item.orig_id_str):
            print(id_item.orig_id_str,"抽奖动态已开奖","正在删除您的动态：",id_item.id_str)
            remove(id_item.id_str)
        id_len = id_len-1#不管动态是否需要删除，都更新id_len的值，因为我们是根据索引获取id_str的值，如果不递减，会陷入死循环
        print(id_len)


if __name__ == '__main__':
    main()
